package pers.ht.mbpo.service;

import net.sf.json.JSONArray;
import pers.ht.mbpo.bean.Admin;
import pers.ht.mbpo.dao.AdminDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.Date;
import java.util.List;

@WebServlet("/AdminServlet")
public class AdminServlet extends HttpServlet {
    private AdminDao adminDao = new AdminDao();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String action = request.getParameter("action");
        if ("insert".equals(action)){
            adminDao.insert(new Admin(request.getParameter("username"),request.getParameter("password"),request.getParameter("nickname")));
            response.sendRedirect("AdminServlet?action=query");
        }
        if ("update".equals(action)){
            adminDao.edit(new Admin(request.getParameter("username"),request.getParameter("password"),request.getParameter("nickname")));
            response.sendRedirect("AdminServlet?action=query");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/xml");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if("query".equals(action)){
            List<Admin> admins = adminDao.query();
            String adminJson = JSONArray.fromObject(admins).toString();
            request.setAttribute("adminJson",adminJson);
            request.getRequestDispatcher("admin/admin.jsp").forward(request, response);
        }
        if ("delete".equals(action)){
            String username = request.getParameter("username");
            adminDao.delete(username);
            response.sendRedirect("AdminServlet?action=query");
        }
        if ("find".equals(action)){
            String adminId = request.getParameter("username");
            Admin admin = adminDao.queryOne(adminId);
            request.setAttribute("admin",admin);
            request.setAttribute("flag",true);
            request.getRequestDispatcher("admin/AEAdmin.jsp").forward(request, response);
        }
        if ("add".equals(action)) {
            request.getRequestDispatcher("admin/AEAdmin.jsp").forward(request, response);
        }
        if ("reSetPwd".equals(action)) {
            String username = request.getParameter("username");
            adminDao.reSetPwd(username);
            response.sendRedirect("AdminServlet?action=query");
        }
    }
}
